import { expect } from '@jest/globals';
import fs from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { addOhPackageDevDps } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';
import {isLinux} from "@ohos/hvigor-common";

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

const testFunBuilder: () => TestCaseFun = () => async (project, taskConfig, record) => {
  // 工程主目录
  const projectRoot = project.projectRootPath();

  await addOhPackageDevDps(projectRoot, { '@ohos/hypium': '1.0.13' });

  // 拼接命令行
  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    module: 'entry',
    tasks: isLinux() ? 'default@UnitTestArkTS' : 'test'
  });
  const result = await runHvigorAsync(projectRoot, commands);

  record.addStep('执行test，模块构建成功&生成覆盖率测试报告', result);
  const moduleNames = project.getModuleNames();

  // 检测每个模块的产物
  moduleNames.forEach(moduleName => {
    const moduleRootPath = project.getModule(moduleName).moduleRootPath();

    // linux不支持localTest
    if (isLinux()) {
      const moduleAbc = path.resolve(moduleRootPath, 'build/default/intermediates/assets/default/ets/modules.abc');
      expect(fs.existsSync(moduleAbc)).toBeTruthy();
    } else {
      const reportPath = path.resolve(moduleRootPath, '.test', 'default', 'outputs', 'test', 'reports');
      expect(fs.existsSync(reportPath)).toBeTruthy();
    }
  });

  expect(result.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('UNIT-TEST-START-IN-SHELL')
  .description('支持直接调用./hvigorw test生成测试报告')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.defaultOpt())
  .testFun(testFunBuilder())
  .load();
